<template>
  <div class="login">
    <div class="box">
      <h3>用户名密码登录</h3>
      <el-input v-model="id" placeholder="用户名" ref="user-name"></el-input>
      <el-input v-model="password" placeholder="密码" ref="pwd" show-password></el-input>
      <el-button type="primary" class="button log" v-on:click="login">登录</el-button>
      <h4>没有账号？</h4>
      <router-link to="/register"><el-button type="primary" class="button reg">点我注册</el-button></router-link>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: 'LoginView',
  data() {
    return {
      id: '',
      password:'',
      loginInfo:''
    }
  },
  methods: {
    async login() {
      let passwd = this.$refs.pwd.value;
      let uid= this.$refs["user-name"].value;
      let logintype = '';
      let uname = '';
      let email = '';
      let phone = '';
      var allNumber = true;
      for (var i = 0; i < uid.length; i++) {
        if(uid.charAt(i) === '@'){
          email = uid;
          logintype = 'e_mail';
          break;
        }
        if(!(uid.charAt(i) >= '0' && uid.charAt(i) <='9')){
          allNumber = false;
        }
      }
      if(logintype !== 'e_mail'){
        if(allNumber && uid.length === 11){
          logintype = 'phone_number';
          phone = uid;
        }
        else {
          logintype = 'username';
          uname = uid;
        }
      }
      console.log(uid);
      console.log(passwd);
      console.log(logintype);
      let {data} = await axios.post('http://localhost:8080/login',
          {type:logintype, e_mail:email, phone_number:phone, username:uname, password:passwd});
      console.log(data);
      this.loginInfo = data;
      switch (data.errno){
        case '3001':
          alert("用户名不存在！");
          break;
        case '3002':
          alert("密码错误！");
          break;
        case '1':
          this.$store.state.isLogin = true;
          this.$store.state.uid = uid;
          alert("登录成功！");
          await this.$router.push('/');
          break;
        default:
          alert("未知错误，登录失败");
          break;
      }
    },
  }
}
</script>

<style scoped lang="scss">
.login{
  padding:10px;
}
.box{
  position: fixed;
  width:400px;
  height:400px;
  border:1px solid #ccc;
  left:0;
  right:0;
  top:0;
  bottom:0;
  margin:auto;
  line-height: 80px;
  background: lightblue;
  padding:10px;
  h3{
    text-align: center;
    margin:0 10px;
  }
  h4{
    text-align: left;
    margin:80px 0px;
  }
  .button{
    border-radius: 12px;
  }
  .log{
    width:400px;
    position: absolute;
    left:10px;
    top:270px;
  }
  .reg{
    position: absolute;
    left:120px;
    top:350px;
  }
}
</style>